package org.starapp.plugins.freemarker;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class Freemarker {

	Configuration cfg;

	String templateFolder;

	String defaultEncoding = "utf-8";

	Locale defaultLocale;

	public Freemarker() {
		cfg = new Configuration();
	}

	public Freemarker(String templateFolder){
		cfg = new Configuration();
		this.templateFolder = templateFolder;
	}

	public Freemarker(String templateFolder, String encoding){
		cfg = new Configuration();
		this.templateFolder = templateFolder;
		this.defaultEncoding = (encoding == null) ? defaultEncoding : encoding;
	}

	public Freemarker(String templateFolder, String encoding, Locale locale){
		cfg = new Configuration();
		this.templateFolder = templateFolder;
		this.defaultEncoding = (encoding == null) ? defaultEncoding : encoding;
		this.defaultLocale = (locale == null) ? null : locale;
	}

	protected void init() throws IOException {
		cfg.setDirectoryForTemplateLoading(new File(templateFolder));
		cfg.setObjectWrapper(new DefaultObjectWrapper());
		cfg.setDefaultEncoding(defaultEncoding);
		if (defaultLocale != null) {
			cfg.setLocale(defaultLocale);
		}
	}

	@SuppressWarnings("unchecked")
	public static void out(String templateFolder, Map data,
			String templateFileName, Writer out) {
		try {
			Freemarker freemarker = new Freemarker(templateFolder);

			freemarker.init();

			freemarker.process(templateFileName, data, out);

		} catch (FileNotFoundException ee) {
			ee.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException ex) {
			ex.printStackTrace();
		}
	}

	@SuppressWarnings("unchecked")
	protected void process(String templateFileName, Map data, Writer out)
			throws IOException, TemplateException {
		Template temp = cfg.getTemplate(templateFileName);
		temp.process(data, out);
		out.flush();
	}
}
